<?php
namespace app\api\controller;


use app\BaseController;
use think\facade\Filesystem;
use learn\services\UtilService as Util;
use app\Request;
use PDO;
use think\facade\Db;

use learn\utils\Json;
//引用名模板
use app\models\Map;
use app\models\system\SystemGroupData;
use app\models\Question;
use app\models\user\UserDefinite;               //用户操作
use app\models\user\LoanBrowse;
use app\models\product\Loan;
use learn\baidu\BaiduShow;

class Index extends BaseController
{
    public function index () {
        //申请额度配置
        $quota = SystemConfigMore(['website_domain']);

        //海报
        $banner = SystemGroupData::getAllValue("index_poster");

        foreach ($banner as $k=>$v) {
            $v['image'] = str_replace("\\","/",$quota['website_domain'] . $v['image']);
            $banner[$k] = $v;
        }
        //申请额度列表
        $allocation = SystemGroupData::getAllValue("apply_quota_config");

        foreach ($allocation as $k=>$v) {
            $v['image'] = str_replace("\\","/",$quota['website_domain'] . $v['image']);
            $allocation[$k] = $v;
        }

        return app("json")->success(compact("banner","allocation"));
    }


    //网站基本配置
    public function website()   
    {
        $quota = SystemConfigMore(['page_bottom_info','day_max_gold','website_ico','website_domain','loan_top_explain','loan_botton_explain','loan_image_explain','loan_name_explain','loan_ico_explain','loan_max_explain','loan_center_explain','fill_info_remind','repayment_instructions']);

        $quota['website_ico'] = str_replace("\\","/",$quota['website_domain'] . $quota['website_ico']);
        $quota['loan_image_explain'] = str_replace("\\","/",$quota['website_domain'] . $quota['loan_image_explain']);
        $quota['loan_ico_explain'] = str_replace("\\","/",$quota['website_domain'] . $quota['loan_ico_explain']);
        $quota['repayment_instructions'] = explode("\r\n",$quota['repayment_instructions']);

        return app("json")->success($quota);
    }

    //设置信用档案的前提
    public function premise()
    {
        $config = getConfig();

        $data = array();

        foreach($config as $k=>$v){
            for ($i=1;$i<=count($v);$i++) {
                $data[$k][] = ["label"=>$v[$i],'value'=>$i];
            }
        }
        

        return app("json")->success($data);
    }

    
    //上传文件
    public function savefile(Request $request)
    {
        $data = Util::postMore([
            ['uid',0],
            ['type','reception']
        ]);
        $mime = request()->file('file')->getMime();
        if (self::GetFileType($mime) == "image") {
            $savename = Filesystem::putFile($data['type']."images", request()->file('file'));

            $relustData = array();
            switch ($data['type']) {
                case 'portrait':            //身份证人像照
                    break;
                case 'national':            //身份证国徽
                    break;
                case 'positive':            //行驶证正面
                    //验证
                    $result = BaiduShow::vehiclecard(app()->getRootPath() . 'public/upload/'.$savename,['vehicle_license_side'=>"front"]);

                    if ($result['words_result']) {
                        $list = array();
                        $list['vehicle_identification_number'] = $result['words_result']['车辆识别代号']['words'];
                        $list['address'] = $result['words_result']['住址']['words'];
                        $list['date_of_issue'] = $result['words_result']['发证日期']['words'];
                        $list['brand_and_model'] = $result['words_result']['品牌型号']['words'];
                        $list['vehicle_type'] = $result['words_result']['车辆类型']['words'];
                        $list['all'] = $result['words_result']['所有人']['words'];
                        $list['nature_of_use'] = $result['words_result']['使用性质']['words'];
                        $list['engine_number'] = $result['words_result']['发动机号码']['words'];
                        $list['plate_number'] = $result['words_result']['号牌号码']['words'];
                        $list['date_registration'] = $result['words_result']['注册日期']['words'];
                        $relustData['info'] = $list;
                    }else {
                        unlink(app()->getRootPath() . 'public/upload/'.$savename);
                    }


                    break;
                case 'side':                //行驶证反面
                    $result = BaiduShow::vehiclecard(app()->getRootPath() . 'public/upload/'.$savename,['vehicle_license_side'=>'back']);
                    if ($result['words_result']) {
                        $list['calibration'] = $result['words_result']['校验记录']['words'];
                        $list['load_capacity'] = $result['words_result']['核定载质量']['words'];
                        $list['curb_weight'] = $result['words_result']['整备质量']['words'];
                        $list['outline_dimension'] = $result['words_result']['外廓尺寸']['words'];
                        $list['approved_carrying_capacity'] = $result['words_result']['核定载人数']['words'];
                        $list['total_mass'] = $result['words_result']['总质量']['words'];
                        $list['fuel_type'] = $result['words_result']['燃油类型']['words'];
                        $list['quasi_total_traction_mass'] = $result['words_result']['准牵引总质量']['words'];
                        $list['remarks'] = $result['words_result']['备注']['words'];
                        $list['file_number'] = $result['words_result']['档案编号']['words'];
                        $list['plate_number'] = $result['words_result']['号牌号码']['words'];
                        $relustData['info'] = $list;
                    }else {
                        unlink(app()->getRootPath() . 'public/upload/'.$savename);
                    }
                    break;
                case 'room':                //有房凭证
                    break;
                case 'insurance':           //保单凭证
                    break;
                default:                    //普通图片上传
                    break;
            }
            $relustData['filename'] =  "/upload/".$savename;
            return app("json")->success("ok",$relustData);
        }else{
            return app("json")->fail("图片类型错误");
        }
    }

     /**
     * 获取文件类型
     * @param $mime
     * @return string
     */
    public function GetFileType($mime)
    {
        if ($mime == "image/png" || $mime == "image/jpg" || $mime == "image/jpeg" || $mime == "image/gif" || $mime == "image/bpm") return "image";
        elseif ($mime == "video/mp4") return "video";
        elseif ($mime == "audio/amr") return "audio";
    }

    //获取问题
    public function getQuestion()
    {
        $config = questionConfig();
        foreach ($config as $k => $v) {
            $config[$k]["data"] = array();
        }
        $list = Question::where("is_show",1)->select();
        if ($list) $list = $list->toArray();

        foreach ($list as $value) {
            $config[$value['type']]['data'][] = $value;
        }
        return app("json")->success($config);
    }


    //处理地址
    public function getMap()
    {
        $map = Map::where("status",0)->field("id as value,short_name as label")->where("level_type",1)->select()->toArray();

        foreach ($map as &$value) {
            $value['children'] = Map::where("status",0)->field("id as value,short_name as label")->where("parent_id",$value['value'])->select()->toArray();
        }
        foreach ($map as &$value) {
            foreach ($value["children"] as &$item) {
                $item['children'] = Map::where("status",0)->field("id as value,short_name as label")->where("parent_id",$item['value'])->select()->toArray();
            }
        }
        return app("json")->success($map);
    }


    //消息列表
    public function newList(Request $request)
    {
        // 获取用户id
        $uid = $request->uid();
        $number = 0;

        //获取签到配置
        $signConfig = SystemConfigMore(['sign_periods_days','sign_initial_gold','sign_gold_add_number']);
        $signList = [(int)$signConfig['sign_initial_gold']];

        //设置签到
        for ($i=1;$i<$signConfig['sign_periods_days'];$i++) {
            $signList[$i] = $signConfig['sign_initial_gold']+$i*$signConfig['sign_gold_add_number'];
        }


        //获取用户签到了几次
        $pastList = UserDefinite::where("uid",$uid)->where("mold","sign")->where("type",0)->where("pm",1)->where("create_time","<",mktime(0,0,0,date('m'),date('d'),date('Y')))->order("create_time desc")->select();
        if ($pastList) {
            $pastList = $pastList->toArray();
        
            for ($i=0;$i<count($pastList);$i++) {
                $pastList[$i]['create_time'] = strtotime($pastList[$i]['create_time']);
                $beginYesterday=mktime(0,0,0,date('m'),date('d')-($i+1),date('Y'));
                $endYesterday=mktime(0,0,0,date('m'),date('d'),date('Y'))-($i+1);
                if ($pastList[$i]['create_time'] >= $beginYesterday && $pastList[$i]['create_time'] <= $endYesterday) {
                    $number++;
                }else{
                    break;
                }

            }
        }



        //签到提醒
        $is_sign  = Db::name("user_definite")->where("uid",$uid)->where("mold","sign")->where("type",0)->where("pm",1)->whereDay("create_time")->count();

        if ($is_sign>0) {
            $signInfo = Db::name("user_definite")->where("number","<",sprintf("%.2f",$signList[count($signList)-1]))->order("id desc")->find();
            $signs = ['title'=>"您有".($signInfo['number']+$signConfig['sign_gold_add_number'])."金币领取",'time'=>date("Y/m/d",((int)$signInfo["create_time"]+1*24*60*60)),"add_time"=>date("Y/m/d",((int)$signInfo["create_time"]+1*24*60*60))];
        }else {
            $signs = ['title'=>"您有".(int)$signList[$number]."金币领取",'time'=>date("Y/m/d"),'add_time'=>date("Y/m/d")];
        }


        //获取贷款消息
        //查询浏览过贷款    
        $loanList = LoanBrowse::where("uid",$uid)->order("id desc")->limit(2)->select();
        if ($loanList) $loanList = $loanList->toArray();

        foreach ($loanList as &$item) {
            $loan = Loan::where("id",$item['loan_id'])->find();
            $item["name"] = $loan['name'];
            $item['image'] = $loan['image'];
            $item['info'] = $loan['info'];
            $item['url'] = $loan['url'];
            $item['quota'] = $loan['quota'];
            $item['content'] = "您的资质符合放贷初筛,马上补充资料...";
        }

        // 获取消息盒子
        return app("json")->success(compact('signs','loanList'));
    }


}
